package com.geek.factory.interceptor;

import cn.hutool.core.util.StrUtil;
import com.geek.factory.constant.MessageConstant;
import com.geek.factory.exception.AccessTokenInvalidException;
import com.geek.factory.exception.FactoryException;
import com.geek.factory.utils.JwtHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/6/10
 *
 * 登录拦截器
 * 1.implements HandlerInterceptor接口，重写preHandle()，执行位置是在真正执行handler之前
 * 2.生效
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //1.从请求头获取token
    String authorization = request.getHeader("Authorization");

    //2.验证其是否为空
    if(StrUtil.isEmpty(authorization)){
        throw new FactoryException(MessageConstant.TOKEN_EMPTY);
    }
    //以Authorization作为key，以Bearer accessToken作为value
    String token = authorization.substring(7);
    log.info("LoginInterceptor preHandle ~ token = "+token);

    //3.验证访问令牌Token是否过期
    if(JwtHelper.isExpiration(token)){
        throw new AccessTokenInvalidException(MessageConstant.ACCESS_TOKEN_VERIFY_FAIL);
    }

    //4.验证其是否合法
    Long userId = JwtHelper.getUserId(token);
    if(userId == null){
        throw new FactoryException(MessageConstant.TOKEN_ILLEGAL);
    }

    //放行
    return true;
}
}